﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace DeskDict.schema
{
    public class XmlParser
    {
        private static string Serialize(object obj, XmlSerializer serializer)
        {
            string rval = "";

            try
            {
                XmlTextWriter xw = new XmlTextWriter(new MemoryStream(), new UTF8Encoding(false));
                xw.Formatting = Formatting.Indented;
                serializer.Serialize(xw, obj);
                rval = new UTF8Encoding(false).GetString(((MemoryStream)xw.BaseStream).ToArray());
            }
            catch
            {
                // TODO!
            }

            return rval;
        }

        private static object Deserialize(string xml, XmlSerializer serializer)
        {
            object rval = null;

            try
            {
                rval = serializer.Deserialize(new StringReader(xml));
            }
            catch
            {
                // TODO!
            }

            return rval;
        }

        public static string Serialize<T>(T obj)
        {
            return Serialize(obj, new XmlSerializer(typeof(T)));
        }

        public static T Deserialize<T>(string xml)
        {
            return (T)Deserialize(xml, new XmlSerializer(typeof(T)));
        }

    }
}
